package com.redis.lesson.web;

import com.redis.lesson.Utils.ShortUrlGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author gusheng
 * @Date 2021/1/7 10:30
 * @ClassName 类名称
 * @Description 类描述
 * @Version 3.4
 */
@RestController
public class ShortUrlController {

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    private static final String SHORT_URL_KEY="short:url";

    /**
     * 长链接转换为短链接
     * 实现原理：长链接转换为短加密串key，然后存储在redis的hash结构中。
     */
    @GetMapping(value = "/encodeTest")
    public String encode(String url) {
        //一个长链接url转换为4个短加密串key
        String [] keys= ShortUrlGenerator.shortUrl(url);
        //任意取出其中一个，我们就拿第一个
        String key=keys[0];
        //用hash存储，key=加密串，value=原始url
        this.redisTemplate.opsForHash().put(SHORT_URL_KEY,key,url);
        return "http://127.0.0.1:8888/short/"+key;
    }


    /**
     * 重定向到原始的URL
     * 实现原理：通过短加密串KEY到redis找出原始URL，然后重定向出去
     */
    @GetMapping(value = "/short/{key}")
    public void decode(@PathVariable String key) {
         //从redis中找到对应短连接key对应的长连接value
        String url = (String)this.redisTemplate.opsForHash().get(SHORT_URL_KEY, key);
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
